<?php

namespace app\shop\logic;

use app\admin\model\shop\user\Commission;
use app\shop\exception\FailException;
use app\shop\model\user\UserModel;
use app\shop\model\user\UserWithdraw;
use think\facade\Db;

class WithdrawLogic extends BaseLogic
{
    public function __construct()
    {
        $this->model = new UserWithdraw();
    }

    public function addWithdraw($params){
        try {
            $uid = $params['user_id'];
            $num = $params['num']?$params['num']:0;
            $account_name = $params['account_name'];
            $account = $params['account'];
            $account_type = $params['account_type'];
            if(empty($account))throw new FailException('账号不能为空');
            $userModel = new UserModel();
            $money = $userModel->where('id',$uid)->value('commission');
            $after_money = $money - $num;
            if (($money < 0) || ($money < $num)) throw new FailException('佣金不足');
            // 第一步：HTML实体解码
            $withdraw_rate = Db::name('shop_setting')->field('name,value')->where('name','withdraw_rate')->value('value');
            $data = [
                'account_name'  =>$account_name,
                'account'       =>$account,
                'user_id'       =>$uid,
                'amount'        =>$num,
                'before_amount' =>$money,
                'after_amount'  =>$after_money,
                'status'        =>10,
                'type'        => 1,
                'account_type'  =>$account_type,
                'create_time'   =>time(),
                'withdraw_rate'=>$withdraw_rate,
                'received_amount'=>($num-bcmul($num,($withdraw_rate/100),2)),
            ];
            $model = new Commission();
            $res = $model->change($uid,$model::TYPE_Withdrawal,$num);
            if(!$res['status']){
                throw new FailException($res['msg']);
            }
            $this->model->save($data);
        }catch (\Exception $exception){
            throw new FailException($exception->getMessage());
        }

        return true;
    }

}